// 登录与注册模块
import { reqGetCode, reqUserRegister, reqUserLogin, reqGetUserInfo, reqLogout } from "@/api";
import { setToken, getToken, removeToken } from "@/utils/token";

const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone);
    if (result.code == 200) {
      commit("GETCODE", result.data);
    }
  },
  // 用户注册
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  // 用户登录【token】
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data);
    if (result.code == 200) {
      commit("USERLOGIN", result.data.token);
      // 持久化存储 token
      setToken(result.data.token);
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  // 获取用户展示信息
  async getUserInfo({ commit }) {
    let result = await reqGetUserInfo();
    if (result.code == 200) {
      commit("GETUSERINFO", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  // 退出登录
  async userLogout({ commit }) {
    // 只是向服务器发一次请求，通知服务器清除token
    let result = await reqLogout();
    // actions 里不能操作 state 提交 mutatios 清除本地存储数据
    if (result.code === 200) {
      commit("CLEAR");
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
};

const mutations = {
  // 获取验证码
  GETCODE(state, code) {
    state.code = code;
    console.log(state.code);
  },
  // 用户登录【token】
  USERLOGIN(state, token) {
    state.token = token;
  },
  // 获取用户展示信息
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  // 清除本地存储数据
  CLEAR(state) {
    state.token = "";
    state.userInfo = {};
    removeToken();
  },
};

const getters = {};

const state = {
  // 验证码
  code: "",
  // 用户登录标识符 token
  token: getToken(),
  // 用户信息
  userInfo: {},
};

export default {
  actions,
  mutations,
  getters,
  state,
};
